package com.eastshop.user.action;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.eastshop.user.service.UserService;
import com.eastshop.user.vo.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 用户模块的Action类
 * @author admin
 *
 */
public class UserAction extends ActionSupport implements ModelDriven<User>{

	//模型驱动使用的对象
	private User user = new User();
	
	public User getModel() {
		return user;
	}
	
	//注入UserService
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	//接收checkcode
	private String checkcode;
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	/**
	 * 跳转到登录页面
	 */
	public String login(){
		return LOGIN;
	}
	
	/**
	 * 用户登录方法
	 */
	public String loginSubmit(){
		
		//根据用户和密码登录系统
		User existUser = userService.login(user);
		//判断
		if(existUser == null){
			//登录失败
			this.addActionError("登录失败:用户名或密码错误或用户未激活!");
			return LOGIN;
		}else{
			//登录成功
			ServletActionContext.getRequest().getSession().setAttribute("existUser", existUser);
			return "loginSubmit";
		}
		
	}
	
	/**
	 * 跳转到注册页面
	 */
	public String register(){
		return "register";
	}
	
	/**
	 * 用户注册的方法
	 */
	public String registerSubmit(){
		//判断验证码
		//从session中取验证码
		String checkcode1 = (String) ServletActionContext.getRequest().getSession().getAttribute("checkcode");
		if(!checkcode1.equalsIgnoreCase(checkcode)){
			//验证码不正确
			this.addActionError("验证码输入错误!");
			return "checkcodeFail";
		}
		//保存用户
		userService.save(user);
		this.addActionMessage("注册成功!");
		return "msg";
	}
	
	/**
	 * 用户激活的方法
	 */
	public String active(){
		//根据激活码查找用户
		User user1 = userService.findByCode(user.getCode());
		if(user1 == null){
			this.addActionError("激活码传入错误！");
		}else{
			this.addActionError("激活成功！");
			user1.setCode(null);
			user1.setState(1); //0：未激活    1：激活状态
			//更新用户信息
			userService.update(user1);
		}
		
		return "msg";
	}
	
	/**
	 * 根据用户名查找用户
	 * @throws IOException 
	 */
	public String findByUsername() throws IOException{
		user = userService.findByUsername(user.getUsername());
		// 获得response对象,项页面输出:
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		if(user != null){
			//用户名已存在
			response.getWriter().print("<font color='red'>用户名已存在！</font>");
		}else{
			//用户名不存在，即可用
			response.getWriter().print("<font color='green'>用户名可以使用！</font>");
		}
		return NONE;
	}
	
	/**
	 * 登出方法
	 */
	public String logout(){
		ServletActionContext.getRequest().getSession().invalidate();
		return "logout";
	}
}
